<template>
  <div class>
    <div class="card" style="display:flex;justify-content: space-between;">
      <div class>
        <el-input size="mini" prefix-icon="el-icon-search" v-model="roleName" placeholder="输入角色名称进行查询" style="width:200px">
        </el-input>
        <el-button type="primary" size="mini" @click="getList">查询</el-button>
      </div>

      <el-button type="primary" size="mini" @click="getNewChenked">确定</el-button>
    </div>
    <div class="card">
      <div class="box">
        <div class="left">
          <el-tabs tab-position="left" v-model="activeName" @tab-click="handleClick">
            <el-tab-pane v-for="i in list" :key="i.id" :label="i.roleName" :name="i.id"></el-tab-pane>
          </el-tabs>

          <el-pagination
            @current-change="currentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            background
            layout=" prev, jumper, next"
            :total="total"
          ></el-pagination>
        </div>
        <div class="right">
          <el-tabs v-model="activeName1">
            <el-tab-pane label="权限" name="1" >
              <el-tree
              style="max-height:calc(100vh - 246px);overflow:auto;"
                ref="tree"
                :data="functionList"
                show-checkbox
                :props="props"
                node-key="id"
                :default-expanded-keys="checks"
                :default-checked-keys="checks"
              >
                <span class="custom-tree-node" slot-scope="{ node,data }">
                  <span>{{ node.label }}</span>
                  <span v-for="item in data.functionList" :key="item.id">
                    {{item.functionName}}
                    <el-switch @change="switchChange(item)" v-model="item.ownerFlag"></el-switch>
                  </span>
                </span>
              </el-tree>
            </el-tab-pane>
            <el-tab-pane label="用户" name="2">
              <div class="card">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="small"
                  @click="dialogVisible=true"
                >添加</el-button>
              </div>
              <el-table :data="tableData" border style="width: 100%;max-height:calc(100vh - 300px);overflow:auto;" >
                <el-table-column align="center" prop="username" label="用户名"></el-table-column>
                <el-table-column align="center" prop="realName" label="真实姓名"></el-table-column>
                <el-table-column align="center" prop="mobile" label="手机号码"></el-table-column>
                <el-table-column align="center" prop="telephone" label="电话号码"></el-table-column>
                <el-table-column align="center" prop="email" label="电子邮箱"></el-table-column>
                <el-table-column align="center" label="操作" width="100">
                  <template slot-scope="scope">
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      size="small"
                      @click="delUser(scope.$index, scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <el-dialog title="所有用户" width="80%" :visible.sync="dialogVisible" :fullscreen="fullscreen">
      <users ref="user" />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUserOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  edit,
  getUserListByRoleId,
  delRoleUser,
  addRoleUser
} from "./function";
import { getAllFunctionListByRoleId } from "@/functions/menuList";
import users from "@/components/checkUser/uesrs.vue";
export default {
  components: {
    users
  },
  data() {
    return {
      roleName: "",
      total: 0,
      pageSize: 10,
      currentPage: 1,
      fullscreen: false,
      checkList: [], //测试字段
      dialogVisible: false,
      activeName: "",
      activeName1: "1",
      list: [],
      props: {
        label: "functionName",
        children: "children"
      },
      selectflag: false,
      functionList: [],
      checks: [],
      tableData: []
    };
  },
  computed: {},
  mounted() {
    this.init();
  },

  methods: {
    currentChange(n) {
      this.currentPage = n;
      this.getList();
    },
    selectAll(val) {
      if (this.selectflag) {
        this.selectflag = false;
        this.select(this.functionList, false);
      } else {
        this.selectflag = true;
        this.select(this.functionList, true);
      }
    },
    select(val, flag) {
      val.forEach(row => {
        this.$refs.tableTreeRef.toggleRowSelection(row, flag);
        if (row.children && row.children.length > 0) {
          this.select(row.children, flag);
        }
      });
    },
    addUserOk() {
      // console.log(this.$refs.user.selectedTableData)
      let checkedUsers = this.$refs.user.selectedTableData;
      let userids = "";
      checkedUsers.forEach(item => {
        userids += item.id + ",";
      });

      let params = {
        roleId: this.activeName,
        userIds: userids
      };
      addRoleUser(params).then(res => {
        this.dialogVisible = false;
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
          this.getUserListByRoleId();
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },
    switchChange(v) {
      console.log(v);
      if (v.ownerFlag) {
        let id = v.parentId;
        let arr = this.$refs.tree.getCheckedKeys();
        if (arr.indexOf(id) < 0) {
          arr.push(id);
        }
        this.$refs.tree.setCheckedKeys(arr);
      }
    },
    delUser(i, row) {
      let params = {
        roleId: this.activeName,
        userIds: row.id
      };
      delRoleUser(params).then(res => {
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
          this.init();
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      this.toRender();
    },
    async toRender() {
      let params = {
        roleId: this.activeName
      };
      this.functionList = await this.getAllFunctionListByRoleId(params);
      this.getListCkecked();
      this.getUserListByRoleId();
    },
    init() {
      this.getList();
    },
    getList() {
      let params = {
        roleName: this.roleName,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      getList(params).then(res => {
        console.log(res);
        if (res.retHead.code == "0000000") {
          this.list = res.retBody.list;
          this.total = res.retBody.total;
          this.currentPage = res.retBody.pageNum;
          this.activeName = this.list[0].id;
          this.toRender();
        } else {
          this.$message.error("发生错误！");
        }
      });
    },
    getListCkecked() {
      this.checks = [];
      this.deepFor(this.functionList);
    },
    getNewChenked() {
      console.log("getCheckedNodes:");
      console.log(this.$refs.tree.getCheckedNodes()); //菜单id
      console.log("getHalfCheckedNodes:");
      console.log(this.$refs.tree.getHalfCheckedNodes()); //菜单id

      let list = this.$refs.tree.getCheckedNodes();
      console.log("list:");
      console.log(list);

      let arr = []; //功能id
      list.forEach(item => {
        item.functionList.forEach(item1 => {
          if (item1.ownerFlag) {
            arr.push(item1.id);
          }
        });
      });

      let params = {
        roleId: this.activeName,

        functionIds: [
          ...this.$refs.tree.getCheckedKeys(),
          ...this.$refs.tree.getHalfCheckedKeys(),
          ...arr
        ]
        // functionIds: [...this.$refs.tree.getCheckedKeys(), ...arr]
      };
      this.edit(params);
    },
    edit(params) {
      edit(params).then(res => {
        // this.init();
        if (res.retHead.code == "0000000") {
          this.$message.success(res.retHead.message);
        } else {
          this.$message.error("发生错误！");
        }
      });
    },
    deepFor(list) {
      // debugger
      list.forEach(item => {
        if (item.ownerFlag && item.children.length == 0) {
          if (this.checks.indexOf(item.id) < 0) {
            // console.log(item.id);
            this.checks.push(item.id);
          }
        }
        if (item.children.length > 0) {
          this.deepFor(item.children);
        }
      });
      // console.log(this.checks);
    },
    getAllFunctionListByRoleId(params) {
      return new Promise((resolve, reject) => {
        getAllFunctionListByRoleId(params).then(res => {
          console.log(res);
          if (res.retHead.code == "0000000") {
            resolve(res.retBody);
          } else {
            this.$message.error("发生错误！");
          }
        });
      });
    },
    getUserListByRoleId() {
      let params = {
        roleId: this.activeName
      };
      getUserListByRoleId(params).then(res => {
        console.log(res);
        if (res.retHead.code == "0000000") {
          this.tableData = res.retBody.list;
        } else {
          this.$message.error("发生错误！");
        }
      });
    }
  },
  created() {}
};
</script>
<style lang='scss' scoped>
.box {
  overflow: hidden;
  .left,
  .right {
    float: left;
    width: 200px;
  }
  .right {
    width: calc(100% - 200px);
  }
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

/deep/ .el-tree-node__content {
  border: 1px solid #ddd;
  border-bottom: 0;
  padding: 10px;
}

/deep/.el-tree {
  border-bottom: 1px solid #ddd;
}
/deep/.el-tabs--left .el-tabs__header.is-left {
  width: 100%;
  padding-right: 10px;
}
</style>